class Restaurant < ActiveRecord::Base
  validates_presence_of  :name, :phone, :address, :product_category_ids
  
  belongs_to :user
  
  has_many :products
  has_many :restaurant_product_category_memberships
  has_many :product_categories, :through => :restaurant_product_category_memberships
  
  def product_category_ids
    @product_category_ids || product_categories.map(&:id)
  end
  
  def product_category_ids=(ids)
    @product_category_ids = ids.map(&:to_i)
    restaurant_product_category_memberships.each do |membership|
      membership.destroy unless ids.include? membership.product_category_id
    end
   
    ids.each do |id|
      membership = RestaurantProductCategoryMembership.create(:product_category_id => id) unless restaurant_product_category_memberships.any? { |d| d.product_category_id == id }
      self.restaurant_product_category_memberships << membership
    end
  end
end
